package com.zsck.zsali.http;
import com.zsck.zsali.base.BaseModel;
import com.zsck.zsali.base.BaseResponse;

import io.reactivex.observers.DisposableObserver;

public abstract class ApiSubscriber<T> extends DisposableObserver<BaseResponse<T>> {
    private static final String SUCCESS_CODE = "0";
    private static final String NOT_LOGGED_IN_CODE = "402";
    private static final String LOGIN_FAILURE_CODE = "401";

    @Override
    public void onComplete() {

    }

    /**
     * 处理非API异常
     */
    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        onFailure(e, ApiException.exceptionHandler(e));
    }

    public abstract void onFailure(Throwable e, String errorMsg);


    @Override
    public final void onNext(BaseResponse<T> response) {
        BaseResponse baseResponse = (BaseResponse) response;
        if (SUCCESS_CODE.equals(baseResponse.getCode())) {
            onSuccess( response.getData());
        } else if (baseResponse.getMessage().equals("缺少登录令牌")||baseResponse.getMessage().equals("登录令牌已超期")||baseResponse.getMessage().equals("登录令牌格式不正确")||NOT_LOGGED_IN_CODE.equals(baseResponse.getCode()) || LOGIN_FAILURE_CODE.equals(baseResponse.getCode())) {
            reLogin();
        } else {
            onFailure(new RuntimeException(baseResponse.getCode()), baseResponse.getMessage());
        }
    }

    private void reLogin(){
    }

    public abstract void onSuccess(T t);

}
